跳到主要内容

Go 交互式命令行工具库 survey

Survey 项目是一个终端的交互工具

go get github.com/AlecAivazis/survey/v2

使用例:

package main

import (
"fmt"
"github.com/AlecAivazis/survey/v2"
)

// the questions to ask
var qs = []*survey.Question{
{
Name: "name",
Prompt: &survey.Input{Message: "What is your name?"},
Validate: survey.Required,
Transform: survey.Title,
},
{
Name: "color",
Prompt: &survey.Select{
Message: "Choose a color:",
Options: []string{"red", "blue", "green"},
Default: "red",
},
},
{
Name: "age",
Prompt: &survey.Input{Message: "How old are you?"},
},
}

func main() {
// the answers will be written to this struct
answers := struct {
Name string // survey will match the question and field names
FavoriteColor string `survey:"color"` // or you can tag fields to match a specific name
Age int // if the types don't match, survey will convert it
}{}

// perform the questions
err := survey.Ask(qs, &answers)
if err != nil {
fmt.Println(err.Error())
return
}

fmt.Printf("%s chose %s.", answers.Name, answers.FavoriteColor)
}

20220523202632

里面提供了很多的输入模式(具体看 Readme)

  • 普通输入框
  • 建议选择框
  • 多行输入
  • 密码输入框
  • 确认框
  • 选择框
  • 多选框
  • 启用编辑器(VIM)